/**
 * @file    app_can_comm.c
 * @brief   用户任务-CAN通信任务
 * @author  Liuwei
 * @version 1.0.1
 * @date    2023-04-30
 * 
 * @copyright Copyright (c) 2023 JBD-Energy Storage Technology Co. LTD
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version   <th>Author   <th>Description
 * <tr><td>2023-04-30 <td>1.0.1     <td>Liuwei   <td>首次创建
 * <tr><td>2024-01-05 <td>1.0.1     <td>Liuwei   <td>修改CAN波特率设置问题，波特率根据协议关联
 * </table>
 */

/* includes ------------------------------------------------------------------*/
#include "app_can_comm.h"
#include "FreeRTOS.h"
#include "task.h"
#include "If_can.h"
#include "app_monitor.h"
#include "cfg_prj.h"
#include "parallel_can.h"
#include "pcs_can_mng.h"
#include "parallel.h"
/* macro/define --------------------------------------------------------------*/
#define APP_CAN_COMM_TASK_CYCLE             (20) 
#define CAN_RST_DLY                         (5000)
/* typedef -------------------------------------------------------------------*/

/* local functions -----------------------------------------------------------*/

/* static variables ----------------------------------------------------------*/
static uint32_t can_rst_cnt = 0;
/* global variables ----------------------------------------------------------*/

/** ------------------------------------------------------------------------- *
  *                             Global function
 ** ------------------------------------------------------------------------- */
/**
 * @brief CAN通信任务
*/
void vCANCommTask(void *pvParameters)
{   
    uint32_t task_cycle = 0;
    portTickType xLastExecutionTime;

    xLastExecutionTime = xTaskGetTickCount();

    If_can_init(CAN_ID1 , pcs_can_get_com_rate());

    task_run_reset(TASK_ID_CAN_COMM);
	
    vTaskDelayUntil( &xLastExecutionTime, 500); // 等待500ms才上传报文，避免数据未完成导致数据上传错误
	
    while(1)
    {
		task_cycle = task_get_cycle(TASK_ID_CAN_COMM);
		if(task_cycle > 20 * APP_CAN_COMM_TASK_CYCLE)
			task_cycle = APP_CAN_COMM_TASK_CYCLE;
			
        can_pcs_comm_mmg(CAN_ID1 , task_cycle);

        task_run_count(TASK_ID_CAN_COMM);
		
		can_rst_cnt += APP_CAN_COMM_TASK_CYCLE;
		if(can_rst_cnt >= CAN_RST_DLY)
		{
			If_can_init(CAN_ID1 , pcs_can_get_com_rate());
			can_rst_cnt = 0;
		}
        
        vTaskDelayUntil( &xLastExecutionTime, APP_CAN_COMM_TASK_CYCLE );
    }
}

/** ------------------------------------------------------------------------- *
  *                              Local function
 ** ------------------------------------------------------------------------- */
 
/********** Copyright (c) 2023 JBD-Energy Storage Technology Co. LTD *********/


